<template>
  <el-dialog :title="title" :visible.sync="showUpdateDialog" width="600px">
    <div class="base-modal-content">
      <!-- 内容主体区域 -->
      <el-form label-position="top" >
        <el-form-item label="模板名称" required>
          <el-input v-model="item.name" placeholder="请输入模板名称" maxlength="6" :disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="模板内容" required>
          <el-input v-model="item.applyContent" placeholder="请输入模板内容" type="textarea" :autosize="{ minRows: 2 }"></el-input>
        </el-form-item>
        <el-form-item label="选择字段">
          <div class="select-field">
            <el-select
              v-model="selectModule"
              placeholder="选择模块"
              @change="moduleChange"
            >
              <el-option
                v-for="item in selectModules"
                :key="item.moduleId"
                :label="item.moduleName"
                :value="item.moduleId"
              ></el-option>
            </el-select>
            <el-select
              v-model="selectField"
              placeholder="选择字段"
              style="margin:0 15px;"
            >
              <el-option
                v-for="item in fieldList"
                :key="item.fieldValue"
                :label="item.filedName"
                :value="item.fieldValue"
              ></el-option>
            </el-select>
            <el-button type="primary" @click="addField">插入字段</el-button>
          </div>
        </el-form-item>
      </el-form>

      <div style="font-size: 13px;color: #dd4b39;">
        <p>模板填写规范</p>
        <p>1.模板内容可添加多个变量，变量格式由系统自动生成不可变更</p>
        <p>2.系统变量每种仅限使用一次</p>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="showUpdateDialog = false">取 消</el-button>
      <el-button type="primary" @click="update" :disabled="pending">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'sms-template',
  data() {
    return {
      pending: false,
      showUpdateDialog: false,
      item: {
        id: 0,
        name: '',
        applyContent: '',
        notice: '自定义通知'
      },
      selectModule: '',
      selectModules: [],
      fieldList:[],
      selectField: '',
      disabled: false
    }
  }, 
  computed: {
    title() {
      return this.item.id ? '编辑短信模版' : '申请短信模版' 
    },
  },
  methods: {
    moduleChange (value) {
      this.selectModule = value;
      let current = {};
      for (let index = 0; index < this.selectModules.length; index++) {
        if(this.selectModules[index].moduleId === value) {
          current = this.selectModules[index]
          break;
        }
      }
      this.fieldList = current.fieldList || [];
    },
    openDialog(item) {
      this.reset();
      if(item) {
        this.item.id = item.id;
        this.item.name = item.name;
        this.item.applyContent = item.applyContent || item.allowContent;
        this.item.notice = item.notice;
        this.disabled = item.id && item.notice != '自定义通知';
        this.getTemplateFields(item.notice);
      } else {
        this.disabled = false;
        this.getTemplateFields('自定义通知');
      }
      this.showUpdateDialog = true;
    },
    reset(){
      this.item = {
        id: 0,
        name: '',
        applyContent: '',
        notice: '自定义通知'
      };
      this.selectModule = '';
      this.selectModules = [];
      this.fieldList = [];
      this.selectField = '';
    },
    getTemplateFields(template){
      this.$http.get('/vipsms/getTemplateFields', { template }).then(res=>{
        if (res && res.status == 0 && res.data && res.data.length) {
          this.selectModules = res.data
        }
      })
    },
    addField(){
      if(!this.selectModule) return this.$platform.notification({
        type: 'error',
        title: '失败',
        message: '请选择模块'
      });
      if(!this.selectField) return this.$platform.notification({
        type: 'error',
        title: '失败',
        message: '请选择字段'
      });
      
      if(this.item.applyContent.indexOf(this.selectField) > -1) {
        const { filedName } = this.fieldList.find(item=>item.fieldValue == this.selectField);
        return this.$platform.notification({
          type: 'error',
          title: '失败',
          message: `[${filedName}]该字段已存在，请勿重复添加`
        });
      }
       
      this.item.applyContent += `{${ this.selectField }}`;
    },
    async update(){
      if (!this.item.name) {
        return this.$platform.notification({
          type: 'error',
          title: '失败',
          message: '模板名称不能为空'
        });
      }
      if (!this.item.applyContent) {
        return this.$platform.notification({
          type: 'error',
          title: '失败',
          message: '模板内容不能为空'
        });
      }
      if (this.item.notice.indexOf('含回访') != -1) {
        if (this.item.applyContent.indexOf('{url}') == -1) {
          return this.$platform.notification({
            type: 'error',
            title: '失败',
            message: '回访模版必须包含链接地址 {url} 字段'
          });
        }
      }
      const params = this.item;
      params.type = '0';
      this.$http.get('/vipsms/applyTemplate', params).then(res=>{
        if (res.succ) {
          this.$platform.notification({
            type: 'success',
            title: '成功',
            message: '保存成功'
          });
          this.$emit('updateSmsTemplate');
          this.showUpdateDialog = false;
        } else {
          this.$platform.notification({
            type: 'error',
            title: '失败',
            message: res.message
          });
        }
      });
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep.el-dialog__headerbtn {
  top: 0!important;
}
.el-dialog__body {
  .select-field {
    display: flex;
  }
}
</style>